package com.xmc.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {


	public static String sentGet(String url, String cookie1) {
		BasicCookieStore cookieStore = new BasicCookieStore();
		BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",cookie1 );
		cookie.setVersion(0);
		cookie.setDomain("jwxt.gdupt.edu.cn");
		cookie.setPath("/");
		cookieStore.addCookie(cookie);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

		HttpClient httpClient = null;
		CookieStore httpCookieStore = new BasicCookieStore();

		/* do stuff */
		HttpGet httpRequest = new HttpGet(url);
		HttpResponse httpResponse = null;
		String result = null;
		try {
			httpClient= httpClientBuilder.setDefaultCookieStore(cookieStore).build();
			httpResponse = httpClient.execute(httpRequest);
			int statusCode = httpResponse.getStatusLine().getStatusCode();// 响应状态码
			if (statusCode == 200) {// 响应成功
				HttpEntity httpEntity = httpResponse.getEntity(); //获取响应实体
				result = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Throwable error) {
			throw new RuntimeException(error);
		}
		return result;
	}




	public static String getCookie(String urlStr) {
		HttpClient http = null;
		CookieStore httpCookieStore = new BasicCookieStore();
		http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
		/* do stuff */
		HttpGet httpRequest = new HttpGet(urlStr);
		HttpResponse httpResponse = null;
		try {httpResponse = http.execute(httpRequest);} catch (Throwable error) {throw new RuntimeException(error);}
		List<Cookie> cookies = httpCookieStore.getCookies();
		System.out.println(cookies);
		return cookies.get(0).getValue();
	}
	


	public static String sendPost(String urlStr, Map<String, String> paramMap,String str) {
		if (urlStr == null) {
			return null;
		}
		if (paramMap == null) {
			return null;
		}
		// 1.创建post请求
		HttpPost httpPost = new HttpPost(urlStr);
		BasicCookieStore cookieStore = new BasicCookieStore();
		BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",str );
		cookie.setVersion(0);
		cookie.setDomain("jwxt.gdupt.edu.cn");
		cookie.setPath("/");
		cookieStore.addCookie(cookie);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// 2.装配post请求参数
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		System.out.println(list);
		String resposeBody = null;// 存储响应数据
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
			httpPost.setEntity(urlEncodedFormEntity);
			// 3.发送请求
			httpClient= httpClientBuilder.setDefaultCookieStore(cookieStore).build();
			response = httpClient.execute(httpPost);
			// 4.处理响应
			int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
			if (statusCode == 200) {// 响应成功
				HttpEntity httpEntity = response.getEntity(); //获取响应实体
				resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4.释放资源
			closeAll(response, httpClient, httpPost);
		}
		return resposeBody;
	}


	/**
	 * 发送POST请求
	 * 
	 * @param urlStr
	 *            请求地址
	 * @param paramMap
	 *            请求参数
	 * @return 返回响应数据字符串（响应失败，返回null）
	 */
	public static String sendPost2(String urlStr, Map<String, String> paramMap,String str) {
		if (urlStr == null) {
			return null;
		}
		if (paramMap == null) {
			return null;
		}
		// 1.创建post请求
		HttpPost httpPost = new HttpPost(urlStr);
		BasicCookieStore cookieStore = new BasicCookieStore();
		BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",str );
		cookie.setVersion(0);
		cookie.setDomain("jwxt.gdupt.edu.cn");
		cookie.setPath("/");
		cookieStore.addCookie(cookie);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// 2.装配post请求参数
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		System.out.println(list);
		String resposeBody = null;// 存储响应数据
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
			httpPost.setEntity(urlEncodedFormEntity);
			// 3.发送请求
			 httpClient= httpClientBuilder.setDefaultCookieStore(cookieStore).build();
			 response = httpClient.execute(httpPost);
			// 4.处理响应
			int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
			if (statusCode == 200) {// 响应成功
				HttpEntity httpEntity = response.getEntity(); //获取响应实体
				resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4.释放资源
			closeAll(response, httpClient, httpPost);
		}
		return resposeBody;
	}

	/**
	 * 发送Delete请求
	 * 
	 * @param urlStr
	 *            请求地址
	 * @return 返回响应数据字符串（响应失败，返回null）
	 */
	public static String sendDelete(String urlStr) {
		if (urlStr == null) {
			return null;
		}

		// 1.创建delete请求
		HttpDelete httpDelete = new HttpDelete(urlStr);
		// 2.发送请求
		String resposeBody = null;// 存储响应数据
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			response = httpClient.execute(httpDelete);
			// 3.处理响应
			int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
			if (statusCode == 200) {
				HttpEntity httpEntity = response.getEntity();
				resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4.释放资源
			closeAll(response, httpClient, httpDelete);
		}
		return resposeBody;
	}

	/**
	 * 发送PUT请求
	 * 
	 * @param urlStr
	 *            请求地址
	 * @return 返回响应数据字符串（响应失败，返回null）
	 */
	public static String sendPut(String urlStr) {
		if (urlStr == null) {
			return null;
		}
		// 1.创建put请求
		HttpPut httpPut = new HttpPut(urlStr);
		// 2.发送请求
		String resposeBody = null;// 存储响应数据
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			response = httpClient.execute(httpPut);
			// 3.处理响应
			int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
			if (statusCode == 200) {
				HttpEntity httpEntity = response.getEntity();
				resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4.释放资源
			closeAll(response, httpClient, httpPut);
		}
		return resposeBody;
	}

	/**
	 * 释放资源
	 * 
	 * @param response
	 * @param httpClient
	 * @param httpRequest
	 */
	private static void closeAll(CloseableHttpResponse response, CloseableHttpClient httpClient,
			HttpRequestBase httpRequest) {
		try {
			if (response != null) {
				response.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}
			if (httpRequest != null) {
				httpRequest.releaseConnection();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

